package cn.tedu.eguser1.controller;

import cn.tedu.eguser1.mapper.UserMapper;
import cn.tedu.eguser1.pojo.dto.UserAddParam;
import cn.tedu.eguser1.pojo.dto.UserUpdateParam;
import cn.tedu.eguser1.pojo.entity.User;
import cn.tedu.eguser1.pojo.vo.UserListVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/v1/user/")
public class UserController {
   @Autowired
   private UserMapper userMapper;

    /**
     * 1.添加用户
     */
    @PostMapping("add")
    public String add(UserAddParam userAddParam){
        System.out.println("userAddParam = " + userAddParam);
        User user = new User();
        BeanUtils.copyProperties(userAddParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        int rows = userMapper.insertUser(user);

        if (rows > 0){
            return "添加用户成功";
        }

        return "添加用户失败";
    }

    /**
     * 2.用户列表功能
     */
    @GetMapping("list")
    public List<UserListVO> list(){
        return userMapper.selectUserList();
    }

    /**
     * 3.删除指定用户功能
     */
    @PostMapping("del")
    public String del(Long id){
        System.out.println("id = " + id);
        int rows = userMapper.deleteUserById(id);
        if (rows > 0){
            return "删除成功";
        }
        return "删除失败";
    }

    /**
     * 4.更新指定用户功能
     */
    @PostMapping("update")
    public String update(UserUpdateParam userUpdateParam){
        System.out.println("userUpdateParam = " + userUpdateParam);
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam, user);
        //处理更新时间
        user.setUpdateTime(new Date());
        //调用接口方法
        int rows = userMapper.updateUser(user);
        if (rows > 0){
            return "更新成功";
        }
        return "更新失败";
    }
}







